<template>
  <div ref="chartDom" :style="{ width: '100%', height: props.height || '400px' }"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, defineProps } from 'vue'
import * as echarts from 'echarts'

interface ChartData {
  columns: string[]
  rows: Record<string, number | string>[]
}

const props = defineProps<{
  chartData: ChartData
  height?: string
}>()

const chartDom = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
  if (!chartDom.value) return

  chartInstance = echarts.init(chartDom.value, 'dark')

  const xAxisData = props.chartData.rows.map(row => row[props.chartData.columns[0]])
  const seriesData = props.chartData.rows.map(row => row[props.chartData.columns[1]])

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: props.chartData.columns[1],
        type: 'line',
        data: seriesData,
        smooth: true
      }
    ]
  }

  chartInstance.setOption(option)
}

const resizeHandler = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeHandler)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeHandler)
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

watch(
  () => props.chartData,
  () => {
    initChart()
  },
  { deep: true }
)
</script>
